package service

import (
	"fmt"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"net/url"
	"strconv"
	"strings"
	"xianzhi/models"
	"xianzhi/utils"
	"github.com/360EntSecGroup-Skylar/excelize"
	"xianzhi/utils/pinyin"
)

// 获取学校信息
func GetSchoolInfo(p map[string]interface{}) *models.School {
	o := orm.NewOrm()
	school := &models.School{}
	qs := o.QueryTable("School")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	if _, ok := p["name"]; ok {
		qs = qs.Filter("name", p["name"])
	}
	if _, ok := p["status"]; ok {
		qs = qs.Filter("status", p["status"])
	}
	qs.One(school)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		if school.Id > 0 {
			school.StatusShow = models.SchoolStatus[school.Status]
			school.IsExcellentShow = models.SchoolIsExcellent[school.IsExcellent]
			school.IsAssistShow = models.SchoolIsAssist[school.IsAssist]
		}
	}
	return school
}

// 添加学校
func AddSchool(input url.Values) (int64, error) {
	o := orm.NewOrm()
	school := &models.School{}
	province := &models.Region{}
	if _, ok := input["province_id"]; ok {
		province.Id = utils.Atoi64(input["province_id"][0])
		o.Read(province)
	}
	school.Province = province
	city := &models.Region{}
	if _, ok := input["city_id"]; ok {
		city.Id = utils.Atoi64(input["city_id"][0])
		o.Read(city)
	}
	school.City = city
	var cityPinYin string
	if city.Id > 0 {
		cityPinYin, _ = pinyin.To_Py(city.Name, "", pinyin.InitialsInCapitals)
	}
	school.CityPinYin = cityPinYin
	if _, ok := input["name"]; ok {
		school.Name = input["name"][0]
	}
	if _, ok := input["introduce"]; ok {
		school.Introduce = input["introduce"][0]
	}
	if _, ok := input["bai_ke_url"]; ok {
		school.BaiKeUrl = input["bai_ke_url"][0]
	}
	if _, ok := input["public_space_url"]; ok {
		school.PublicSpaceUrl = input["public_space_url"][0]
	}
	if _, ok := input["is_excellent"]; ok {
		school.IsExcellent, _ = strconv.Atoi(input["is_excellent"][0])
	}
	if _, ok := input["is_assist"]; ok {
		school.IsAssist, _ = strconv.Atoi(input["is_assist"][0])
	}
	if _, ok := input["status"]; ok {
		school.Status, _ = strconv.Atoi(input["status"][0])
	}
	return o.Insert(school)
}

// 从上传的excel添加学校
func AddSchoolFromExcel(input url.Values) (int64, error) {
	pinyin.LoadingPYFileName("./static/pinyin.txt")
	f, err := excelize.OpenFile("." + input["excel_file_path"][0])
	if err != nil {
		logs.Info("can not open excel file:", err)
		return 0, err
	}
	o := orm.NewOrm()
	school := models.School{}
	province := &models.Region{}
	if _, ok := input["province_id"]; ok {
		province.Id = utils.Atoi64(input["province_id"][0])
		o.Read(province)
	}
	school.Province = province
	city := &models.Region{}
	if _, ok := input["city_id"]; ok {
		city.Id = utils.Atoi64(input["city_id"][0])
		o.Read(city)
	}
	school.City = city
	var cityPinYin string
	if city.Id > 0 {
		cityPinYin, _ = pinyin.To_Py(city.Name, "", pinyin.InitialsInCapitals)
	}
	var schools []models.School
	rows := f.GetRows("Sheet1")
	for k, row := range rows {
		if k == 0 {
			continue
		}
		school.Name = row[0]
		school.Introduce = row[1]
		school.BaiKeUrl = row[2]
		school.PublicSpaceUrl = row[3]
		school.IsExcellent, _ = strconv.Atoi(row[4])
		school.IsAssist, _ = strconv.Atoi(row[5])
		school.Status = 1
		school.CityPinYin = cityPinYin
		schools = append(schools, school)
	}
	return o.InsertMulti(1, schools)
}

// 修改学校信息
func EditSchool(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	return o.QueryTable("School").Filter("id", input["id"][0]).Update(p)
}

// 获取学校列表
func GetSchoolList(p map[string]interface{}) (int64, []*models.School) {
	var schoolList []*models.School
	o := orm.NewOrm()
	qs := o.QueryTable("School")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["provinceId"]; ok {
		qs = qs.Filter("province_id", p["provinceId"])
	}
	if _, ok := p["cityId"]; ok {
		qs = qs.Filter("city_id", p["cityId"])
	}
	if _, ok := p["name"]; ok {
		qs = qs.Filter("name__contains", p["name"])
	}
	if _, ok := p["isExcellent"]; ok {
		qs = qs.Filter("is_excellent", p["isExcellent"])
	}
	if _, ok := p["isAssist"]; ok {
		qs = qs.Filter("is_assist", p["isAssist"])
	}
	if _, ok := p["status"]; ok {
		qs = qs.Filter("status", p["status"])
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.OrderBy("city_pin_yin").All(&schoolList)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		for _, school := range schoolList {
			school.StatusShow = models.SchoolStatus[school.Status]
			school.IsExcellentShow = models.SchoolIsExcellent[school.IsExcellent]
			school.IsAssistShow = models.SchoolIsAssist[school.IsAssist]
		}
	}
	if _, ok := p["selectedSchoolIds"]; ok {
		selectedSchoolIdArr := strings.Split(p["selectedSchoolIds"].(string), ",")
		var schoolId string
		for _, school := range schoolList {
			schoolId = fmt.Sprintf("%d", school.Id)
			for _, selectedSchoolId := range selectedSchoolIdArr {
				 if schoolId == selectedSchoolId {
				 	school.IsSelected = 1
				 	break
				 }
			}
		}
	}
	return totalCount, schoolList
}
